package model;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Crypto {
    private static final String AES_ALGORITHM = "AES"; // 使用AES算法进行加密
    private static final String AES_KEY = "0123456789abcdef"; // 加密密钥（较为简单）

    public static String encrypt(String plaintext) throws Exception {
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM); // 获取 AES 算法的加密实例
        SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), AES_ALGORITHM); // 使用密钥生成 
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); // 初始化加密实例
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); // 加密
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String ciphertext) throws Exception {
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM); // 获取 AES 算法的解密实例
        SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), AES_ALGORITHM); // 密钥生成 
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); // 初始化解密实例
        byte[] decodedBytes = Base64.getDecoder().decode(ciphertext);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes); // 解密
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}
